import { UsageManager } from '../../utils/usage';

Page({
  data: {
    myName: '',
    friendName: '',
    place: '',
    remainingUsage: 0
  },

  onLoad() {
    this.updateRemainingUsage();
  },

  onShow() {
    this.updateRemainingUsage();
  },

  updateRemainingUsage() {
    const remaining = UsageManager.getRemainingUsage();
    this.setData({ remainingUsage: remaining });
  },

  handleSubmit() {
    if (this.data.remainingUsage <= 0) {
      wx.showToast({
        title: '今日生成次数已用完',
        icon: 'none'
      });
      return;
    }

    const { myName, friendName, place } = this.data;
    
    if (!myName || !friendName || !place) {
      wx.showToast({
        title: '请填写所有信息',
        icon: 'none'
      });
      return;
    }

    // 增加使用次数
    if (!UsageManager.incrementUsage()) {
      wx.showToast({
        title: '今日生成次数已用完',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '提交中...'
    });

    wx.request({
      url: 'https://api.coze.cn/v1/workflow/run',
      method: 'POST',
      header: {
        'Authorization': 'Bearer pat_ZvmvCBCfAQsxT3zv5E6D6JKQGmb61OzkC6rHpJGE7vDHrnV2HjcNwbnppdiNp2DG',
        'Content-Type': 'application/json'
      },
      data: {
        workflow_id: "7447825465739509772",
        parameters: {
          object: place,
          name: friendName,
          my_name: myName
        }
      },
      success: (res: any) => {
        wx.hideLoading();
        if (res.data && res.data.code === 0) {
          try {
            const outputData = JSON.parse(res.data.data);
            const imageUrl = outputData.output;
            
            wx.navigateTo({
              url: `/pages/result/result?imageUrl=${encodeURIComponent(imageUrl)}`
            });
          } catch (e) {
            wx.showToast({
              title: '数据解析失败',
              icon: 'error'
            });
          }
        } else {
          wx.showToast({
            title: '请求失败',
            icon: 'error'
          });
        }
      },
      fail: (error) => {
        wx.hideLoading();
        wx.showToast({
          title: '提交失败',
          icon: 'error'
        });
        console.error('请求失败：', error);
      }
    });
  }
}); 